<template>
  <contentModel v-if="contentShow" :title="conTitle" @close="handleClose">
    <template #footer>
      <a-button type="primary" @click="handleSave">保存</a-button></template
    >
    <!-- 标题 -->
    <a-form ref="formRef" :model="formValue" :layout="layout" :rules="rules">
      <sub-title class="sub-title">添加</sub-title>
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-item field="secretLevel" label="密级:">
            <secretLevelSelect
              v-model:model-value="formValue.secretLevel"
              disabled
              :default-value="formValue.secretLevel"
            />
          </a-form-item>
        </a-col>
        <!-- ordStatus   制单状态 ^ 通用代码 PMS_ORDER_ORD_STATUS : 0-编制中，5-已确认，10-审批中,15-审批通过,20-审批不通过，25-已签订 -->
        <!-- billStatus  单据状态 ^ 通用代码 PMS_ORDER_BILL_STATUS :0-未交付,5-交付中,10-部分入库,20-全部入库,25-暂停,30-撤销 -->
        <a-col :span="8">
          <a-form-item field="orderNo" label="订单号:">
            <inputModal
              v-model="formValue.orderNo"
              :label-value="'orderNo'"
              :value-name="'sysOrderNo'"
              :label-name="'sysOrderNo'"
              title="采购订单选择"
              :type="'orderCode'"
              :default-query="{ ordStatus: '15,25', billStatus: '0' }"
              @handle-ok="selectOrder"
              @handerClear="handerClearOrderNo"
            /> </a-form-item
        ></a-col>
        <a-col :span="8">
          <a-form-item field="contractNo" label="合同编号:">
            <a-input
              v-model="formValue.contractNo"
              disabled
              placeholder="请输入合同编号" /></a-form-item
        ></a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-item field="billNo" label="变更单号:">
            <a-input
              v-model="formValue.billNo"
              disabled
              placeholder="请输入变更单号" /></a-form-item
        ></a-col>
        <a-col :span="8">
          <a-form-item field="listChangeFlag" label="是否变更正文:">
            <a-radio-group v-model="formValue.listChangeFlag">
              <a-radio value="Y">是</a-radio>
              <a-radio value="N">否</a-radio>
            </a-radio-group></a-form-item
          >
        </a-col>
      </a-row>

      <a-row :gutter="6">
        <a-col :span="12">
          <a-form-item field="filesName" label="附件:">
            <a-space>
              <fileUpload
                v-model="fileValue"
                type="1"
                btn-name="文件上传"
                title="Excel导入"
                accept=".xlsx,.doc,.pdf,.jpg"
                :max-size="10"
              />
              <div>
                <span>当前选中文件：</span
                ><span
                  style="color: #165dff; cursor: pointer"
                  @click="handleFile"
                  >{{ fileValue.name }}</span
                >
                <span
                  v-if="fileValue.name"
                  style="margin-left: 16px; color: red; cursor: pointer"
                  @click="delFile"
                  >x</span
                >
              </div>
            </a-space>
          </a-form-item>
        </a-col>
      </a-row>

      <sub-title class="sub-title">订单主信息变更</sub-title>

      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-item
            field="orderChangeType"
            label="变更类型:"
            label-col-flex="400px"
          >
            <dict-select
              v-model="formValue.orderChangeType"
              allow-clear
              dict-type="pmsOrderChangeType"
              placeholder="请选择"
            ></dict-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item field="mdsTempletIdNew" label="订单模板:">
            <inputModal
              v-model="formValue.mdsTempletIdNew"
              :label-value="'mdsTempletIdNew'"
              :value-name="'templateCode'"
              :label-name="'templateName'"
              title="订单模板选择"
              :type="'orderTemp'"
            /> </a-form-item
        ></a-col>
        <a-col :span="8">
          <a-form-item field="abroadFlagNew" label="国内/外采购:">
            <dict-select
              v-model="formValue.abroadFlagNew"
              allow-clear
              dict-type="abroadFlag"
              placeholder="请选择" /></a-form-item
        ></a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-item field="signDateTimeNew" label="签订日期:">
            <a-date-picker
              v-model="formValue.signDateTimeNew"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%" /></a-form-item
        ></a-col>
        <!-- 新增  编辑 文本密级去掉 -->
        <a-col :span="8">
          <a-form-item field="orderSecretLevelNew" label="文本密级:">
            <secretLevelSelect
              v-model:model-value="formValue.orderSecretLevelNew"
              disabled
              :default-value="formValue.orderSecretLevelNew" /></a-form-item
        ></a-col>
      </a-row>

      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-item
            field="orderChangeReason"
            label="变更原因:"
            label-col-flex="400px"
          >
            <a-textarea
              v-model="formValue.orderChangeReason"
              placeholder="最大输入300字符"
              :max-length="300"
              allow-clear
              show-word-limit
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-item field="noteNew" label="备注:" label-col-flex="400px">
            <a-textarea
              v-model="formValue.noteNew"
              placeholder="最大输入300字符"
              :max-length="300"
              allow-clear
              show-word-limit
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <sub-title class="sub-title">订单主信息子表信息</sub-title>
    <div>
      <a-space>
        <a-button
          type="primary"
          style="margin-bottom: 16px"
          @click="addAlterationOrder"
          >添加变更订单</a-button
        >
        <inputModal
          ref="selectRef"
          :input-show="false"
          :label-value="'sysOrderNo'"
          :value-name="'orderNo'"
          :label-name="'sysOrderNo'"
          title="订单明细选择"
          :default-query="{
            pmsOrderId: formValue.pmsOrderId,
          }"
          :type="'orderCodeDetail'"
          @handle-ok="selectOrderDetail"
        />
      </a-space>

      <editTable
        ref="editTableRef"
        :table-data="tableData"
        :columns="columns"
        :secret-level-select="true"
        :show-add="false"
      >
        <template #ordChngTypeName>
          <!-- <span>{{ 'U' }}---</span> -->
          <span>{{ '修改' }}</span>
        </template>
        <template #proMdsItemIdNew="{ record }">
          <!-- <a-input
            v-model="record.proMdsItemIdNew"
            placeholder="请输入"
          ></a-input> -->
          <inputModal
            v-model="record.proMdsItemIdNew"
            :label-value="record.proMdsItemCodeNew"
            :value-name="'id'"
            :label-name="'materialCode'"
            title="机型"
            :default-query="{
              materialType: '6',
              materialStatus: '1,3',
            }"
            :type="'materialCode'"
            @handle-ok="(row) => selectMillTypeCode(row, record)"
            @handerClear="handerClearDate(record)"
          />
        </template>
        <template #agreeementCodeNew="{ record }">
          <a-input
            v-model="record.agreeementCodeNew"
            placeholder="请输入"
          ></a-input>
        </template>
        <template #workRouteNew="{ record }">
          <a-input v-model="record.workRouteNew" placeholder="请输入"></a-input>
        </template>
        <template #operation="{ rowIndex }">
          <a-space>
            <a-button type="text" @click="del(rowIndex)">删除</a-button>
          </a-space>
        </template>
      </editTable>
    </div>
  </contentModel>
</template>

<script lang="ts" setup>
  import inputModal from '@/common/components/search-modal/input-modal.vue';
  import dictSelect from '@/common/components/dict-select/index.vue';
  import secretLevelSelect from '@/common/components/cac-components/secret-level-select/index.vue';
  import editTable from '@/common/components/edit-table/index.vue';
  import { ref, defineAsyncComponent, nextTick } from 'vue';
  import fileUpload from '@/common/components/file-upload-page/index.vue';
  import { Message } from '@arco-design/web-vue';
  import subTitle from '@/common/components/title/sub-title.vue';
  import modalPromise from '@/common/utils/modal-promise';
  import {
    saveHandle,
    changeOrder,
    editHandle,
  } from '@/api/purchase-order/orderApi';
  import columns from './mymodalcolums';

  defineProps({
    contentShow: { type: Boolean, default: false },
  });
  const childNum = ref('0');
  const emit = defineEmits(['update:contentShow', 'modelCancel']);
  const contentModel = defineAsyncComponent(
    () => import('@/common/components/content-model/index.vue')
  );
  const handleClose = () => {
    emit('update:contentShow', false);
    emit('modelCancel');
  };
  const formRef = ref();
  // 删除
  const del = async (index: any) => {
    try {
      await modalPromise.info({
        title: '请确认',
        content: '您确定要删除当前数据？',
        hideCancel: false,
      });
    } catch {
      return;
    }
    tableData.value.splice(index, 1);
    Message.success({
      content: '删除成功!',
    });
  };
  const delFile = async () => {
    try {
      await modalPromise.info({
        title: '请确认',
        content: '您确定要删除当前附件？',
        hideCancel: false,
      });
    } catch {
      return;
    }
    fileValue.value = {};
    Message.success({
      content: '删除成功!',
    });
  };
  const selectOrder = (val) => {
    console.log(val, 'selectOrder');
    nextTick(() => {
      formValue.value.orderNo = val.sysOrderNo;
      formValue.value.contractNo = val.orderNo;
      formValue.value.pmsOrderId = val.id;
      formValue.value.mdsVendorId = val.mdsVendorCode;
      formValue.value.mdsVendorName = val.mdsVendorName;
      childNum.value = val.pmsOrderLCount;
      // 新增 编辑 密级 文本密级置灰 订单号选择一条数据 回显  密级 文本密级 不可修改
      formValue.value.secretLevel = val.secretLevel;
      formValue.value.orderSecretLevelNew = val.secretLevel;
    });
    console.log(val);
  };
  const selectOrderDetail = (val) => {
    console.log(val, 'val++++++++++++++++++++');

    console.log(val, tableData.value, '----');
    val.pmsOrderLId = val.id;
    console.log(val.pmsOrderLId, '  val.pmsOrderLId  val.pmsOrderLId');
    val.id = null;
    val.pmsOrderLNo = val.serialNo;
    val.contractNo = val.orderNo;
    val.orderNo = val.sysOrderNo;
    const status = tableData.value.every(
      (v) => v.pmsOrderLId !== val.pmsOrderLId
    );
    console.log(tableData, 'tableDatatableDatatableDatatableData');

    if (!status) {
      Message.warning('不可重复添加!');
    } else {
      tableData.value.push(val);
    }
  };
  const conTitle = ref('');
  const layout = ref('vertical');
  const formValue = ref({
    secretLevel: '',
    orderNo: '',
    contractNo: '',
    billNo: '',
    aircraftTypeMarkOption: '',
    listChangeFlag: '',
    orderChangeType: '',
    mdsTempletIdNew: '',
    abroadFlagNew: '',
    signDateTimeNew: '',
    orderSecretLevelNew: '',
    orderChangeReason: '',
    noteNew: '',
    ordChngType: '',
  });
  const fileValue = ref({});
  const handleSave = async () => {
    formRef.value.validate(async (validate) => {
      if (!validate) {
        const params = {
          ...formValue.value,
          orderChangeDetailVOList: tableData.value,
          orderAttachmentVO: fileValue.value.name
            ? {
                filesName: fileValue.value.name,
                filesUrl: fileValue.value.url,
                secretLevel: formValue.value.secretLevel,
              }
            : null,
        };

        const { data } = formValue.value.id
          ? await editHandle(params)
          : await saveHandle(params);
        if (data) {
          Message.success('操作成功!');
          handleClose();
        }
      }
    });
  };
  const handleFile = () => {
    window.open(fileValue.value.url);
  };
  const rules = {
    secretLevel: [
      {
        required: true,
        message: '请选择密级',
      },
    ],
    orderChangeType: [
      {
        required: true,
        message: '请选择变更类型',
      },
    ],
  };
  const tableData = ref([]);
  const init = async (val) => {
    console.log(val, 'initinitinit');
    if (val) {
      const { data } = await changeOrder(val);
      // 点击编辑  密级置灰不可选   选择订单号带数据
      delete data.secretLevel;
      delete data.orderSecretLevelNew;

      formValue.value = Object.assign(formValue.value, data);
      tableData.value = data.orderChangeDetailVOList || [];
      fileValue.value = {
        name: data.orderAttachmentVO.filesName,
        url: data.orderAttachmentVO.filesUrl,
      };
    } else {
      formValue.value = Object.assign(formValue.value, {
        secretLevel: '',
        orderNo: '',
        contractNo: '',
        billNo: '',
        aircraftTypeMarkOption: '',
        listChangeFlag: '',
        orderChangeType: '',
        mdsTempletIdNew: '',
        abroadFlagNew: '',
        signDateTimeNew: '',
        orderSecretLevelNew: '',
        orderChangeReason: '',
        noteNew: '',
        ordChngType: '',
      });
    }
  };
  const selectRef = ref();
  const addAlterationOrder = () => {
    if (!formValue.value.orderNo) {
      Message.warning('请先选择订单!');
      return;
    }
    if (childNum.value && childNum.value !== '0') {
      selectRef.value.select();
    } else {
      Message.warning('请选择有订单明细记录数的数据!');
    }
    // addAlterationOrderFlag.value = true;
  };
  const selectMillTypeCode = (row, record) => {
    record.proMdsItemCodeNew = row.materialCode;
  };

  const handerClearDate = (record) => {
    record.proMdsItemCodeNew = '';
  };
  const handerClearOrderNo = () => {
    formValue.value.secretLevel = '';
    formValue.value.orderSecretLevelNew = '';
  };
  defineExpose({ init, conTitle });
</script>

<style lang="less" scoped>
  .modal-footer-box {
    display: flex;
    justify-content: right;
    margin-top: 10px;
    margin-right: 26px;
  }

  .sub-title {
    margin-bottom: 16px;
    text-align: left;
  }
</style>
